import React, { useEffect, useState, useRef } from 'react';
import { Input, Button, Tree, Popconfirm, message, Modal, Form, Cascader } from 'antd';
import { } from 'antd';
import { getList, getShow } from '../../apis/department/list';
import "../../static/css/Department/DepartmentList.css"
import { getDel } from '../../apis/department/del';
import { useNavigate } from 'react-router';
import { getParentIdList } from '../../utils/treeUtils';
import { getDetails,postUp } from "../../apis/department/upShow"

const DepartmentList: React.FC = (): JSX.Element => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const navigate = useNavigate()
  const [data, setData] = useState<any>()
  const [input, setInput] = useState<any>()
  const codeInfo: any = useRef()
  const [form] = Form.useForm();
  const [list, setList] = useState<any>()
  const [id, setId] = useState<number>(0)
  // 删除，点击确认
  const confirm: any = (id: number) => {
    return () => {
      delInfo(id)
      message.success('删除成功');

    }


    // delInfo(id)
  };
  // 删除，点击取消
  const cancel: any = (e: React.MouseEvent<HTMLElement>) => {
    // console.log(e);
    message.error('取消删除');
  };
  // 请求列表数据
  const getListInfo = async () => {
    const res: any = await getList()
    if (res.code === '00000') {
      // console.log(res.data);
      setData(toParse(res.data))


    } else {
      message.error(res.msg);
    }


  }
  var depArr: any = []
  const getModalInfo = async () => {
    const res: any = await getList()
    if (res.code === '00000') {
      // console.log(res.data);
      setList(res.data)
      depArr = res.data

    } else {
      message.error(res.msg);
    }


  }
  // 查询请求数据
  const getShowInfo = async (id: any) => {
    const res: any = await getShow({ id })

    if (res.code === '00000') {
      console.log(res);

      // setData(res.data)
    }

  }
  // 二次封装删除接口
  const delInfo = async (id: number) => {
    const res: any = await getDel(id)
    console.log(res);
    if (res.code === '00000') {
      getListInfo()
    }

  }
  // 点击添加跳转添加页面
  const addTo = () => {
    navigate('/department/add_upd')
  }
  // 获取input内容
  const inputChang = (e: any) => {
    setInput(e.target.value)
  }
  // 点击input调用查询
  const getInput = () => {
    getShowInfo(input)

  }
  useEffect(() => {
    // 列表调用请求
    getListInfo()
    getModalInfo()
  }, [])
  const jsxTree = (name: string, id: number, show: any) => {
    return () => (
      <div className='tree'>
        <div>{name}</div>
        <div>
          <Button className="addButton" size="small" type="primary" onClick={showModal(name, id, show)}>修改</Button>
          <Popconfirm
            title="是否确认删除?"
            onConfirm={confirm(id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button type="primary" size="small" danger>删除</Button>
          </Popconfirm>
        </div>
      </div>
    )
  }
  // 循环添加按钮方法
  function toParse(arr: any) {
    arr.map(function (item: any) {
      item.name = jsxTree(item.name, item.id, item)
      if (item.son.length > 0 && Array.isArray(item.son)) {
        toParse(item.son)
      }
    })
    return arr
  }

  const showModal = (name: string, id: number, show: any) => {
    return async () => {
      setIsModalVisible(true);
      getModalInfo()
      
      console.log(show);
      
      // 根据id查询单条数据
      const res: any = await getDetails(id)
      if (res.code === '00000') {
        setId(res.data.id)
        const showFrom = { ...res.data, name, parent_id: getParentIdList(depArr, id) }
        codeInfo.current.setFieldsValue(showFrom)
      }
    }


  };
  // 点击修改
  const postUpInfo=async (id:number,params:any)=>{
    const res:any=await postUp(id,params)
    if(res.code==='00000'){
      message.success('修改成功')
      getListInfo()
    }else{
      message.error(res.msg)
    }
    
  }
  const onFinish = (values: any) => {
   if(values.parent_id){
    setIsModalVisible(false);
    const params={...values,parent_id:values.parent_id.length>=1 ?  values.parent_id[values.parent_id.length-1]:0}
    
    postUpInfo(id,params)
   }
  };
  const onChange: any = (value: any) => {
    console.log(value);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const onReset = () => {
    form.resetFields();
};

  return (
    <div className="departmentListBody">
      <div className="top">
        <div className="input">
          <Input placeholder="请输入部门" onChange={inputChang} />
        </div>
        <Button type="primary" onClick={getInput}>查询</Button>
        <Button className="addButton" type="primary" onClick={addTo}>添加</Button>
      </div>
      <div style={{ width: '500px' }}> <Tree defaultExpandAll={true} treeData={data} fieldNames={{ title: "name", key: "id", children: "son" }} blockNode={true} /></div>
      {
        isModalVisible &&
        <Modal title="修改" visible={isModalVisible} footer={null} onCancel={handleCancel} okType="primary" >
          <Form
            name="basic"
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 6 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
            form={form}
            ref={codeInfo}
          >
            <Form.Item
              label="选择父级部门"
              name="parent_id"
            >
              <Cascader size="small" fieldNames={{ label: "name", value: "id", children: "son" }} options={list} onChange={onChange} placeholder="请选择" />
            </Form.Item>
            <Form.Item
              label="部门名称"
              name="name"
              rules={[{ required: true, message: '请输入部门名称' }]}
            >
              <Input size="small" />
            </Form.Item>
            <Form.Item
              label="负责人名称"
              name="user"
              rules={[{ required: true, message: '请输入负责人名称' }]}
            >
              <Input size="small" />
            </Form.Item>
            <Form.Item
              label="负责人手机号"
              name="user_mobile"
              rules={[{ pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的手机号' }]}
            >
              <Input size="small" />
            </Form.Item>
            <Form.Item
              label="openid"
              name="openid"
              rules={[{ required: true, message: '请输入openid' }]}
            >
              <Input size="small" />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 3, span: 6 }}>
              <Button htmlType="button" onClick={onReset} style={{ backgroundColor: '#909399', color: '#fff', border: 'none', marginRight: '10px' }}>
                重置
              </Button>
              <Button type="primary" htmlType="submit" style={{ border: 'none' }}>
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      }
    </div>
  )
}
export default DepartmentList